package threadpool;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinPoolDemo {
    public static void main(String[] args) {

        ForkJoinPool forkJoinPool = new ForkJoinPool(4);

        int[] data  =  new int[10000];
        Arrays.fill(data, 1);


        Integer result = forkJoinPool.invoke(new MyForJoinTask(data, 0, data.length));
        System.out.println(result);

    }
}


class MyForJoinTask extends RecursiveTask<Integer>{

    int[] data;
    int start;
    int end;

    public MyForJoinTask(int[] data, int start, int end) {
        this.data = data;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {

        if(end - start <= 2000){
            // 任务够小，直接计算结果
            int sum = 0;
            for(int i = start; i < end;i++){
                sum += data[i];
            }
            return sum;
        }else{
            // 任务太大，还要继续拆分
            int mid = (start+end)/2;
            // 利用中间值，创建两个子任务
            MyForJoinTask left = new MyForJoinTask(data, start, mid);
            MyForJoinTask right = new MyForJoinTask(data, mid, end);

            left.fork();

            Integer rightResult = right.compute();
            Integer leftResult = left.join();

            return rightResult + leftResult;
        }
    }
}